package com.shkco.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shkco.domain.*;
import com.shkco.dto.StockDto;
import com.shkco.exception.GlobalExceptionCode;
import com.shkco.feign.ProductService;
import com.shkco.feign.PurchaseService;
import com.shkco.feign.UserService;
import com.shkco.mapper.StockLogMapper;
import com.shkco.mapper.StockMapper;
import com.shkco.mapper.StockWarningLogMapper;
import com.shkco.result.JSONResult;
import com.shkco.service.IStockService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.shkco.utils.AssertUtil;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale
 * @since 2022-09-29
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    @Autowired
    private ProductService productService;

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private StockWarningLogMapper stockWarningLogMapper;

    @Autowired
    private StockLogMapper stockLogMapper;


    @Value("${stockwarninglog.info}")
    private String info;

    @Override
    public void inBound(StockDto stockDto) {
        JSONResult porductJson = productService.get(stockDto.getProductId());
        AssertUtil.isTrue(porductJson.isSuccess(), GlobalExceptionCode.ERROR);
        Object data = porductJson.getData();
        AssertUtil.isNotNull(data,GlobalExceptionCode.ERROR);
        String jsonString = JSONObject.toJSONString(data);
        Product product = JSON.parseObject(jsonString, Product.class);
        Stock stock = stockMapper.selectByProductId(product.getId());
        // 保存采购订单
        purchaseApplySave(stockDto, product);
        // 保存采购日志
        purchaseLogSave(stockDto, product);
    }

    @Override
    public void outBound(Long id) {
        JSONResult jsonResult = purchaseService.get(id);
        AssertUtil.isTrue(jsonResult.isSuccess(), GlobalExceptionCode.ERROR);
        Object data = jsonResult.getData();
        AssertUtil.isNotNull(data,GlobalExceptionCode.ERROR);
        String jsonString = JSONObject.toJSONString(data);
        PurchaseApply purchaseApply = JSON.parseObject(jsonString, PurchaseApply.class);
        // 设置通过状态
        purchaseApply.setStatus(1);
        // 根据采购申请单获取user信息
        Long userId = purchaseApply.getUserId();
        User user = getUser(userId);
        // 获取商品信息
        Long productId = purchaseApply.getProductId();
        Product product = getProduct(productId);
        // 根据采购申请单获取商品库存
        Stock stock = stockMapper.selectByProductId(purchaseApply.getProductId());
        AssertUtil.isNotNull(stock,GlobalExceptionCode.ERROR);
        // 获取采购数量
        Integer count = purchaseApply.getCount();
        // 库存数量
        Integer inventory = stock.getCount();
        // 判断库存是否小于采购数量
        boolean b = inventory < count;
        AssertUtil.isFalse(b,GlobalExceptionCode.INVENTORY_INSUFFICIENT);
        // 判断库存是否小于10，如果小于10记录警告日志
        if (inventory < 10){
            saveWarningLog(product, inventory);
        }
        // 剩余库存
        int remain = inventory - count;
        stock.setCount(remain);
        stock.setUpdateTime(new Date());
        // 获取商品价格
        BigDecimal price = product.getPrice();
        // 获取用户余额
        BigDecimal balance = user.getBalance();
        // 采购商品总价
        BigDecimal total = price.multiply(BigDecimal.valueOf(count));
        // 判断用户余额是否大于等于采购商品总价
        boolean b1 = balance.compareTo(total) == 0;
        boolean b2 = balance.compareTo(total) == 1;
        AssertUtil.isFalse(b1 && b2,GlobalExceptionCode.BANLANCE_INSUFFICIENT);
        // 采购后余额
        BigDecimal balanc = balance.subtract(total);
        user.setBalance(balanc);
        saveStockLong(product, count);

        purchaseService.saveOrUpdate(purchaseApply);
        userService.saveOrUpdate(user);
        stockMapper.update(stock,null);
    }

    @Override
    public void noOutBound(Long id) {
        JSONResult jsonResult = purchaseService.get(id);
        AssertUtil.isTrue(jsonResult.isSuccess(), GlobalExceptionCode.ERROR);
        Object data = jsonResult.getData();
        AssertUtil.isNotNull(data,GlobalExceptionCode.ERROR);
        String jsonString = JSONObject.toJSONString(data);
        PurchaseApply purchaseApply = JSON.parseObject(jsonString, PurchaseApply.class);
        purchaseApply.setStatus(2);
        purchaseService.saveOrUpdate(purchaseApply);
    }

    private void saveStockLong(Product product, Integer count) {
        // 保存出库日志
        StockLog stockLog = new StockLog();
        stockLog.setCreateTime(new Date());
        stockLog.setStatus(1);
        stockLog.setProductId(product.getId());
        stockLog.setProductName(product.getProductName());
        stockLog.setTypeId(product.getTypeId());
        stockLog.setCount(count);
        stockLogMapper.insert(stockLog);
    }

    private void saveWarningLog(Product product, Integer inventory) {
        StockWarningLog stockWarningLog = new StockWarningLog();
        stockWarningLog.setCreateTime(new Date());
        stockWarningLog.setProductId(product.getId());
        stockWarningLog.setProductName(product.getProductName());
        stockWarningLog.setCurrentCount(inventory);
        stockWarningLog.setInfo(info);
        stockWarningLogMapper.insert(stockWarningLog);
    }

    private Product getProduct(Long productId) {
        JSONResult jsonResult1 = productService.get(productId);
        AssertUtil.isTrue(jsonResult1.isSuccess(), GlobalExceptionCode.ERROR);
        Object data1 = jsonResult1.getData();
        AssertUtil.isNotNull(data1,GlobalExceptionCode.ERROR);
        String jsonString1 = JSONObject.toJSONString(data1);
        Product product = JSON.parseObject(jsonString1, Product.class);
        return product;
    }

    private User getUser(Long userId) {
        JSONResult jsonResult1 = userService.get(userId);
        AssertUtil.isTrue(jsonResult1.isSuccess(), GlobalExceptionCode.ERROR);
        Object data1 = jsonResult1.getData();
        AssertUtil.isNotNull(data1,GlobalExceptionCode.ERROR);
        String jsonString1 = JSONObject.toJSONString(data1);
        User user = JSON.parseObject(jsonString1, User.class);
        return user;
    }

    private void purchaseLogSave(StockDto stockDto, Product product) {
        PurchaseLog purchaseLog = new PurchaseLog();
        purchaseLog.setCount(stockDto.getCount());
        purchaseLog.setCreateTime(new Date());
        purchaseLog.setProductId(product.getId());
        purchaseLog.setProductName(product.getProductName());
        purchaseService.saveOrUpdate(purchaseLog);
    }

    private void purchaseApplySave(StockDto stockDto, Product product) {
        // 保存采购单
        PurchaseApply purchaseApply = new PurchaseApply();
        // Status审批 0等待审批  1审批通过  2审批不通过
        purchaseApply.setStatus(0);
        purchaseApply.setCount(stockDto.getCount());
        purchaseApply.setCreateTime(new Date());
        purchaseApply.setProductId(stockDto.getProductId());
        purchaseApply.setProductName(product.getProductName());
        purchaseApply.setUserId(stockDto.getUserId());
        purchaseService.saveOrUpdate(purchaseApply);
    }

    @Test
    public void test() throws Exception{
        BigDecimal a = BigDecimal.valueOf(100);
        Integer integer = Integer.valueOf(String.valueOf(a));
        System.out.println(integer);
    }
}
